package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.RoleDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.Role;
import com.itheima.health.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author ：zhao
 * @date ：Created in 2020/1/2 0002
 * @description ：角色持久层
 * @version: 1.0
 */
@Service
@Slf4j
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;

    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Role> page = roleDao.selectByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public Role findById(Integer id) {

        return roleDao.selectById(id);
    }

    @Override
    public List<Integer> findPermissionIdsByRoleId(Integer id) {
        return roleDao.findPermissionIdsByRoleId(id);
    }

    @Override
    public List<Integer> findMenuIdsByRoleId(Integer id) {
        return roleDao.findMenuIdsByRoleId(id);
    }

    @Override
    public void add(Role role, Integer[] permissionIds, Integer[] menuIds) {
        // 插入基本数据
        roleDao.insert(role);
        //逐条插入关系表数据
        for (Integer permissionId : permissionIds) {
            roleDao.insertRoleAndPermission(role.getId(),permissionId);
        }
        for (Integer menuId : menuIds) {
            roleDao.insertRoleAndMenu(role.getId(),menuId);
        }
    }

    @Override
    public void delete(Integer id) {
        roleDao.deleteRoleAndPermission(id);
        roleDao.deleteRoleAndMenu(id);
        roleDao.delete(id);
    }

    @Override
    public void edit(Role role, Integer[] permissionIds, Integer[] menuIds) {
        roleDao.update(role);
        roleDao.deleteRoleAndPermission(role.getId());
        roleDao.deleteRoleAndMenu(role.getId());
        for (Integer permissionId : permissionIds) {
            roleDao.insertRoleAndPermission(role.getId(),permissionId);
        }
        for (Integer menuId : menuIds) {
            roleDao.insertRoleAndMenu(role.getId(), menuId);
        }
    }
}
